const { db } = require('../config/database');

class Conversation {
  /**
   * 创建新的对话记录
   * @param {Object} data - 对话数据
   * @returns {Promise<Object>} - 返回创建的对话记录
   */
  static create(data) {
    const { user_id, title } = data;
    const created_at = new Date().toISOString();

    return new Promise((resolve, reject) => {
      db.run(
        'INSERT INTO conversations (user_id, title, created_at) VALUES (?, ?, ?)',
        [user_id, title || '新对话', created_at],
        function(err) {
          if (err) {
            reject(err);
            return;
          }
          
          resolve({
            id: this.lastID,
            user_id,
            title: title || '新对话',
            created_at
          });
        }
      );
    });
  }

  /**
   * 保存单条消息
   * @param {Object} data - 消息数据
   * @returns {Promise<Object>} - 返回保存的消息
   */
  static saveMessage(data) {
    const { conversation_id, role, content } = data;
    const timestamp = new Date().toISOString();

    return new Promise((resolve, reject) => {
      db.run(
        'INSERT INTO messages (conversation_id, role, content, timestamp) VALUES (?, ?, ?, ?)',
        [conversation_id, role, content, timestamp],
        function(err) {
          if (err) {
            reject(err);
            return;
          }
          
          resolve({
            id: this.lastID,
            conversation_id,
            role,
            content,
            timestamp
          });
        }
      );
    });
  }

  /**
   * 获取用户的所有对话
   * @param {number} userId - 用户ID
   * @returns {Promise<Array>} - 返回对话列表
   */
  static getUserConversations(userId) {
    return new Promise((resolve, reject) => {
      db.all(
        'SELECT * FROM conversations WHERE user_id = ? ORDER BY created_at DESC',
        [userId],
        (err, rows) => {
          if (err) {
            reject(err);
            return;
          }
          resolve(rows);
        }
      );
    });
  }

  /**
   * 获取单个对话的所有消息
   * @param {number} conversationId - 对话ID
   * @returns {Promise<Array>} - 返回消息数组
   */
  static getConversationMessages(conversationId) {
    return new Promise((resolve, reject) => {
      db.all(
        'SELECT * FROM messages WHERE conversation_id = ? ORDER BY timestamp ASC',
        [conversationId],
        (err, rows) => {
          if (err) {
            reject(err);
            return;
          }
          resolve(rows);
        }
      );
    });
  }

  /**
   * 更新对话标题
   * @param {number} id - 对话ID
   * @param {string} title - 新标题
   * @returns {Promise<boolean>} - 返回是否更新成功
   */
  static updateTitle(id, title) {
    return new Promise((resolve, reject) => {
      db.run(
        'UPDATE conversations SET title = ? WHERE id = ?',
        [title, id],
        function(err) {
          if (err) {
            reject(err);
            return;
          }
          resolve(this.changes > 0);
        }
      );
    });
  }

  /**
   * 删除对话及其所有消息
   * @param {number} id - 对话ID
   * @returns {Promise<boolean>} - 返回是否删除成功
   */
  static delete(id) {
    return new Promise((resolve, reject) => {
      // 使用事务确保原子性
      db.serialize(() => {
        db.run('BEGIN TRANSACTION');
        
        db.run('DELETE FROM messages WHERE conversation_id = ?', [id], (err) => {
          if (err) {
            db.run('ROLLBACK');
            reject(err);
            return;
          }
          
          db.run('DELETE FROM conversations WHERE id = ?', [id], function(err) {
            if (err) {
              db.run('ROLLBACK');
              reject(err);
              return;
            }
            
            db.run('COMMIT');
            resolve(this.changes > 0);
          });
        });
      });
    });
  }
}

module.exports = Conversation; 